package com.mashibing.class12;

// 是否是平衡二叉树.
// 平衡二叉树判断条件,
// X为头的树是二叉树
// 1)x的左树是二叉树
// 2)x的右树是二叉树
// 3)X左子树的高度和X的右子树的高度相差的绝对值  小于或等于 1
public class Code03_IsBalanced {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static boolean isBalanced(Node head){
        return process(head).isBlanced;
    }

    public static class Info{
        public boolean isBlanced;// 是否平衡
        public int height; // 高度

        public Info(boolean isBlanced, int height) {
            this.isBlanced = isBlanced;
            this.height = height;
        }
    }

    public static Info process(Node node){
        if (node==null){ // 空树处理
            return new Info(true,0);
        }
        Info leftInfo = process(node.left);
        Info rightInfo = process(node.right);

        boolean isBalanced = true;
        int height = Math.max(leftInfo.height, rightInfo.height)+1;
        if (!leftInfo.isBlanced){
            isBalanced = false;
        }
        if (!rightInfo.isBlanced){
            isBalanced = false;
        }
        if (Math.abs(leftInfo.height-rightInfo.height)>1){
            isBalanced = false;
        }
        return new Info(isBalanced, height);
    }

    // for test
    public static Node generateRandomBST(int maxLevel, int maxValue) {
        return generate(1, maxLevel, maxValue);
    }

    // for test
    public static Node generate(int level, int maxLevel, int maxValue) {
        if (level > maxLevel || Math.random() < 0.5) {
            return null;
        }
        Node head = new Node((int) (Math.random() * maxValue));
        head.left = generate(level + 1, maxLevel, maxValue);
        head.right = generate(level + 1, maxLevel, maxValue);
        return head;
    }

    public static void main(String[] args) {
        int maxLevel = 5;
        int maxValue = 100;
        int testTimes = 1000000;
        for (int i = 0; i < testTimes; i++) {
            Node head = generateRandomBST(maxLevel, maxValue);
//            if (isBalanced(head) != isBalanced2(head)) {
//                System.out.println("Oops!");
//            }
        }
        System.out.println("finish!");
    }
}
